#!/bin/bash
# Copy files and Gentoo packages with lib dependences
# (c) mahatma

ldd="lddtree"

[[ -z "$*" ]] && {
	echo "Usage: $0 outdir \"simple files list\" \"files list\" \"packages list\""
	[[ "$ldd" == "ldd" ]] && echo "(warning: 'ldd' do not work in cross compile, use pre-tracked dependeces)"
	exit 1
}

: ${TMPDIR:=/tmp}
tmpf="$TMPDIR/_files$$.lst"

get_files(){
	local out="$1"
	shift
	local i f f1 f2 f3 ff
	for f in $* ; do
		[[ -z "$f" ]] && continue
		ff="$ROOT$f"
		[[ -e "$ff" ]] || continue
		[[ -e "$out$f" ]] && continue
		echo " + $ff"
		f1=""
		f2="${f%/*}"
		f3=""
		for i in ${f2//\// }; do
			f1="$f1/$i"
			[[ -z "$i" ]] && continue
			get_files "$out" "$f1"
			f3="$f3../"
		done
		if [[ -L "$ff" ]]; then
			f1="`readlink "$ff" 2>/dev/null`"
			[[ "${f1#/}" == "$f1" ]] && f1="$f2/$f1"
			get_files "$out" "$f1"
			ln -s "$f3${f1#/}" "$out$f" || exit 1
		elif [[ -d "$ff" ]]; then
			mkdir "$out$f"
		else
			cp "$ff" "$out/$f" -a || exit 1
		fi
		for i in `$ldd "$ff" 2>/dev/null`; do
			[[ -e "$out$i" ]] && continue
			get_files "$out" "$i"
		done
	done
}

list_pkg(){
	local p
	for p in $* ; do
		sed -e 's:^... ::' -e 's: .*$::' $ROOT/var/db/pkg/$p*/CONTENTS
	done
}

pkg_from(){
	touch $tmpf
	find -L $1 -type f | sort -u >$tmpf.1
	sort -m $tmpf.1 $tmpf |uniq -u|sed -e 's:^'"$1"'\(.*\)$:obj \1 :'|grep -lRFf - $ROOT/var/db/pkg --include=CONTENTS|sed -e 's:/CONTENTS$::' -e "s:^$ROOT/var/db/pkg/::"
	mv $tmpf.1 $tmpf
}

cp_db(){
local i
for i in `pkg_from $1`; do
	echo " * $i"
	mkdir $1/var/db/pkg/${i%/*} --parents 2>/dev/null
	cp $ROOT/var/db/pkg/$i $1/var/db/pkg/$i -a
done
}

rm $tmpf -f
echo "Copying simple files..."
get_files $1 $2
[[ -z "$3$4" ]] && exit
pkg_from $1
echo "Copying packaged files..."
get_files $1 $3
echo "Copying packages..."
get_files $1 $(list_pkg $4)
echo "Copying packages info..."
cp_db $1
rm $tmpf
